package com.digitalchina.lxnsy.activity.old;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessShareFarm;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ShareFarmListVO;
import com.digitalchina.lxnsy.entity.ShareFarmTypeVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.ShareFarmListHolder;
import com.digitalchina.lxnsy.viewholder.ShareFarmTypeHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/8/10 16:37
 * 修改备注：
 * ================================================
 */
public class ShareFarmListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.recycler_tab)
    EasyRecyclerView recyclerTab;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.tv_search)
    EditText tvSearch;
    @Bind(R.id.iv_cancel)
    ImageView ivCancel;

    private RecyclerArrayAdapter adapter;
    private RecyclerArrayAdapter adapterTab;
    private int page = 1;
    private int limit = 10;

    private List<ShareFarmTypeVO> typeList = new ArrayList<>();
    private List<ShareFarmListVO> voList = new ArrayList<>();

    private int msgWhat = -1;
    private String name = "";
    private String type = "";

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_share_farm);
        setTitle("共享三农");
    }

    @Override
    public void initMember() {


        //顶部tab
        recyclerTab.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerTab.setAdapter(adapterTab = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ShareFarmTypeHolder(parent);
            }
        });


        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setDividerDecoration(this, 1, 0, 0));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ShareFarmListHolder(parent);
            }
        });

        BusinessShareFarm.shareFarmType(this, mHandler);

        onRefresh();
    }

    @Override
    public void addListener() {

        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });


        adapterTab.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                for (int i = 0; i < typeList.size(); i++) {
                    typeList.get(i).setChecked(i == position);
                }
                adapterTab.notifyDataSetChanged();


                if (position == 0) {
                    type ="";
                } else {
                    ShareFarmTypeVO vo = (ShareFarmTypeVO) adapterTab.getAllData().get(position);
                    type = vo.getValue();
                }
                onRefresh();
            }
        });


        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                GotoUtil.gotoActivity(ShareFarmListActivity.this, ShareFarmDetailActivity.class, "ShareFarmListVO", adapter.getAllData().get(position));
            }
        });


        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                name = "";
                tvSearch.setText("");
                onRefresh();
            }
        });

        tvSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) textView.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
                    }
                    // 刷新列表数据
                    if (!name.equals(tvSearch.getText().toString())) {
                        name = tvSearch.getText().toString();
                        onRefresh();
                    }
                    return true;
                }
                return false;
            }
        });

    }

    @Override
    public void setHandler() {

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                msgWhat = msg.what;

                switch (msg.what) {
                    case MSG.MSG_SHARE_FARM_TYPE_SUCCESS:
                        typeList = FastJsonUtil.getListBeanRow(msg.obj.toString(), "options", ShareFarmTypeVO.class);
                        setType();
                        break;
                    case MSG.MSG_SHARE_FARM_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_SHARE_FARM_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;

                    case MSG.MSG_GET_LOVE_SHARE_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_SHARE_FARM_TYPE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    // 设置顶部tab类型
    private void setType() {
        if (typeList == null)
            return;

        ShareFarmTypeVO vo1 = new ShareFarmTypeVO();
        vo1.setLabel("全部");
        vo1.setValue("");
        typeList.add(0, vo1);


        for (int i = 0; i < typeList.size(); i++) {
            typeList.get(i).setChecked(i == 0);
        }

        adapterTab.clear();
        adapterTab.addAll(typeList);

    }

    @Override
    public void callBack(Object object) {
        switch (msgWhat) {
            case MSG.MSG_SHARE_FARM_LIST_SUCCESS: // 共享列表
                voList = FastJsonUtil.getListBeanRow(object.toString(), "rows", ShareFarmListVO.class);

                break;
        }

        if (page == 1) { // 刷新
            adapter.clear();
        }

        adapter.addAll(voList);

        if (voList != null) {
            if (voList.size() < limit) {
                adapter.stopMore();
            }
        }
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessShareFarm.shareList(this, page, limit, type, name, "1",mHandler);
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            page++;
            BusinessShareFarm.shareList(this, page, limit, type, name,"1", mHandler);
        }
    }
}
